package com.tianji.learning.Task;

import com.tianji.learning.domain.po.LearningLesson;
import com.tianji.learning.enums.LessonStatus;
import com.tianji.learning.service.ILearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class TaskForExpire {

    private final ILearningLessonService iLearningLessonService;

    @Scheduled(cron = "0 0 0 1 * *")
    public void expireTask(){
        log.info("开始执行课程有效期检查任务");
        // 1.查询所有有效期课程
        List<LearningLesson> lessons = iLearningLessonService.
                lambdaQuery()
                .ne(LearningLesson::getStatus, LessonStatus.EXPIRED)
                .list();
        // 2.判断是否过期
        lessons.forEach(lesson -> {
            if (lesson.getExpireTime().isBefore(LocalDateTime.now())) {
                // 3.如果过期，更新状态
                lesson.setStatus(LessonStatus.EXPIRED);
                iLearningLessonService.updateById(lesson);
            }
        });
    }

}
